import { Button, Statistic,AutoComplete, message, Row, Col, Card, Input, Form } from 'antd';
import React, {
  useState,
  useRef,
  useEffect
} from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, {
  ProColumns,
  ActionType
} from '@ant-design/pro-table';
import ProCard from '@ant-design/pro-card';
import { queryRule,selectActivity, selectStudent,queryInfo,taskExport} from './service';
import { downloadFile } from '@/utils/utils';
import moment from 'moment';
const { Option } = AutoComplete;
const TableList: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const { activityId } = props.location.query
  const [options, setOptions] = useState([]);
  const [uid, setUid] = useState<any>()
  const [firstRender, setFirstRender] = useState(true)
  const statusMap = {
    '0': '未开始',
    '1': '已开始',
    '2': '已完成'
  }
  const taskExportHandler = async function () {
    if(!uid){
      var url = await taskExport({activityId:String(activityId)})
    } else{
      var url = await taskExport({activityId:String(activityId),uid:String(uid)})
    }
    downloadFile(`整体做题统计-${moment(new Date().getTime()).format('YYYY-MM-DD HH-mm-ss')}`,url,'.xls')
  }
  const fetchData = async () => {
    const data = await queryRule({ activityId, pageSize: 20, pageNum: 1 })

    const info = await queryInfo({ activityId })
    setBaseInfo(info.data)
    modifyMsgData(data.data)
  }
  const onSelect = (data: any, option: any) => {
    setUid(option.key)
  };
  const onSearch = async (key: string) => {
    let data = await selectStudent( key )
    function getStudentSearchOptions(keys:any, data:any) {
      return  !keys ? [] : data.result.map((item: { uid: any; nickname: any; phone: any}) => ({
        id: item.uid,
        label: (item.nickname||'') + `  (${item.phone})`,
        value: item.nickname + `  (${item.phone})`
      }))
    }
    let options =  getStudentSearchOptions(key,data)
    setOptions(options);
  };
  const createColumns = (data,gamePaperData) => {
    let columnsMap = new Map()
    data.map(item => {
        columnsMap.set(item.gamePaperId,item.gamePaperName)
    })
    let column = []
      for (var k in gamePaperData) {
       column.push({
         title: columnsMap.get(Number(k)),
         dataIndex: k,
         hideInSearch: true
      })
    }
    setColumns(baseColumns.concat(column))
  }

  const modifyMsgData = (data) => {
   const taskMap = data.columns
   const json = data.dataSource.map(item => {
     for (var k in item.gamePaperData) {
       let json = {}
       json[k] = item.gamePaperData[k]
       item = Object.assign(item, json)
      }
      return item
    })
    createColumns(taskMap, json[0].gamePaperData)
    setFirstRender(false)
    return json
  }

  useEffect(() => {
    if (activityId) {
      fetchData()

    }
  }, [activityId])
  const [columns, setColumns] = useState(baseColumns)
  const [baseInfo, setBaseInfo] = useState<any>()
  const baseColumns: ProColumns<{}>[] = [
     {
      title: '课程ID',
      dataIndex: 'id',
      hideInTable: true,
      hideInSearch: true
    },

    {
      title: '用户id',
      dataIndex: 'uid',
      hideInSearch: true
    },
   {
      title: '课程名称',
      dataIndex: 'key',
      hideInTable: true,
      hideInSearch: true
    },
    {
      title: '用户昵称',
      dataIndex: 'nickname',
      ellipsis:true,
      width: 150,
      copyable: true,
      hideInSearch: true,
      tip: '标题过长会自动收缩',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      hideInSearch: true
    },
    {
      title: '班级',
      dataIndex: 'groupName',
      hideInSearch: true
    },
    {
      title: '辅导老师',
      dataIndex: 'teacherName',
      hideInSearch:true
    }
  ];

  const [form] = Form.useForm();
  const onFinish = () => {
    if (actionRef.current) {
      actionRef.current.reload();
    }
  }
  const onReset = () => {
    window.location.reload()
  };
  return (
    <PageContainer>
      <Card style={{marginBottom:'20px'}}>
        <Form form={form} onFinish={onFinish} style={{'paddingBottom':'0px'}}>
          <Row gutter={[16,16]} >

          <Col span={8}>
            <Form.Item label="用户名" name="key">
              <AutoComplete
                onSelect={onSelect}
                onSearch={onSearch}
                placeholder="请选择"
                onChange={(value) => {
                  if (!value) {
                    setUid()
                  }
                }}
              >
                {options.map((item) => (
                  <Option key={item.id}  label={item.label} value={item.label}>
                    {item.label}
                  </Option>
                ))}
                </AutoComplete>
                </Form.Item>
            </Col>
            <Col span={8} offset={8} style={{textAlign: 'right'}}>
              <Form.Item>
                <Button type="primary" htmlType="submit" style={{marginRight:'10px'} }>
                  查询
                </Button>
                <Button htmlType="button" onClick={onReset}>
                  重置
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>
      { !firstRender  && <ProTable<{}>
        headerTitle="数据列表"
        actionRef={actionRef}
        rowKey="key"
        search={ false}
        request={async params => {
          params.activityId = activityId
          params.uid = uid
          const msg = await queryRule({
            ...params,
            pageNum: params.current
          })
          if (msg.data.dataSource.length === 0) {
            setColumns([])
            return
          }
          return {
            data: modifyMsgData(msg.data),
            success: true,
            total: msg.data.count
          }

        }}
        columns={columns}
        tableExtraRender={(props, dataSource) =>
          baseInfo&&
          <Card>
            <div style={{display:'flex'}}>
              <div
                style={{marginRight:'20px'}}
              >主讲老师 :
              <span style={{fontSize:'17px',paddingLeft:'10px'}}>
                {baseInfo.teacherName}
                </span>
              </div>
              <div
                style={{marginRight:'20px'}}
                >课程进行至:
                <span
                style={{fontSize:'17px',paddingLeft:'10px'}}>
                  {baseInfo.status == 1? baseInfo.classroomName : statusMap[baseInfo.status]}
                </span>
               </div>
            </div>
          </Card>
        }
        toolbar={{
          actions: [
            <Button key="primary" type="primary" onClick={ taskExportHandler}>
              导出整体做题统计
            </Button>,
          ],
        }}
        scroll={{ x: 5000 }}
      />}
    </PageContainer>
  );
};

export default TableList;
